package com.ruoyi.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.domain.HotelOrder;
import com.ruoyi.mapper.HouseMapper;
import com.ruoyi.mapper.OrderMapper;
import com.ruoyi.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderTwoServiceImpl implements OrderTwoService {

    private static Logger hotelSuccess = LoggerFactory.getLogger("hotel_success");

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    ElongService elongService;

    @Autowired
    HouseMapper houseMapper;

    @Autowired
    LogService logService;

    @Autowired
    JurisdictionService jurisdictionService;

    @Autowired
    OrderRegisterService orderRegisterService;

    @Autowired
    RPService rpService;

    @Override
    public List<Map> getOrderList(Map map) {
        if (map.get("orderReqDateRange[0]") != null) {
            map.put("startReqTime", map.get("orderReqDateRange[0]").toString() + " 00:00:00");
        }
        if (map.get("orderReqDateRange[1]") != null) {
            map.put("endReqTime", map.get("orderReqDateRange[1]").toString() + " 23:59:59");
        }

        if (map.get("startTime[0]") != null) {
            map.put("rzStartTime", map.get("startTime[0]").toString());
        }
        if (map.get("startTime[1]") != null) {
            map.put("rzEndTime", map.get("startTime[1]").toString());
        }

        if (map.get("endTime[0]") != null) {
            map.put("ldStartTime", map.get("endTime[0]").toString());
        }
        if (map.get("endTime[1]") != null) {
            map.put("ldEndTime", map.get("endTime[1]").toString());
        }

        if (map.get("handleTime[0]") != null) {
            map.put("handleStartTime", map.get("handleTime[0]").toString());
        }
        if (map.get("handleTime[1]") != null) {
            map.put("handleEndTime", map.get("handleTime[1]").toString());
        }

        map.put("jurisdiction", jurisdictionService.getHotelDataPermissionsAndCompleteSQL());
        return orderMapper.getOrderList(map);
    }

    @Override
    public int orderHandlePost(JSONObject jsonObject) {
        JSONObject jsonObject1 = jsonObject.getJSONObject("dataStr");
        String type = jsonObject.getString("type");
        String eOrderCode = jsonObject1.getString("eOrderCode");
        String orderCode = jsonObject1.getString("orderCode");
        String orderId = jsonObject1.getString("orderId");

        if ("1".equals(type)) {
            // 接受订单,调用发送确认号接口,订单状态修改为1
            String loginToken = elongService.getLoginToken();
            JSONObject jsonObject3 = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject4 = new JSONObject();
            jsonObject4.put("elongOrderId", eOrderCode);
            JSONArray jsonArray1 = new JSONArray();
            jsonArray1.add(orderCode);
            jsonObject4.put("hotelConfirmNumber", jsonArray1);
            jsonObject4.put("notesToElong", "订单已接受");
            jsonObject4.put("pmsOrderId", orderCode);
            jsonArray.add(jsonObject4);
            jsonObject3.put("orderList", jsonArray);

            // 封装发送确认号接口报文
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("accessToken", loginToken);
            jsonObject2.put("apiKey", "testapikey");
            jsonObject2.put("body", jsonObject3);
            jsonObject2.put("encrypted", "0");
            jsonObject2.put("guid", UUID.randomUUID().toString());
            jsonObject2.put("method", "updateHotelConfirmNumber");
            jsonObject2.put("timestamp", System.currentTimeMillis());
            jsonObject2.put("version", "v2");
            hotelSuccess.info("发送确认号:");
            String jsonString = JSONObject.toJSONString(jsonObject2);
            hotelSuccess.info("发送确认号请求报文:" + jsonString);
            String res = HttpUtils.sendPostJson("https://opendc.elong.com/gate/v2/rest?aid=1073742141", jsonString);
            hotelSuccess.info("发送确认号响应报文:" + res);
            JSONObject jsonObject5 = JSONObject.parseObject(res);
            if (jsonObject5.getInteger("retcode") == 0) {
                Map map = new HashMap();
                map.put("orderId", orderId);
                map.put("orderStatus", 1);
                map.put("handleTime", DateUtils.getDate2());
                map.put("orderCode", 1);
                // 修改订单状态
                orderMapper.updateOrder(map);
                // 插入日志表
                logService.insertOrderLog(orderCode, "人工接受订单(新订)", 2);
                // 插入登记表
                orderRegisterService.insertOrderRegister(map);
                return 1;
            } else {
                return 0;
            }
        } else {
            // 拒绝订单,订单状态修改为2
            Map map = new HashMap();
            map.put("orderId", jsonObject1.getString("orderId"));
            map.put("orderStatus", 2);
            map.put("handleTime", DateUtils.getDate2());
            orderMapper.updateOrder(map);
            logService.insertOrderLog(orderCode, "人工拒绝订单(新订)", 2);
            return 1;
        }
    }

    @Override
    public int updateOrderStatusPost(JSONObject jsonObject) {
        JSONObject jsonObject1 = jsonObject.getJSONObject("dataStr");
        String type = jsonObject.getString("type");
        // 看一下这个订单是不是保留房
        String orderCode = jsonObject1.getString("orderCode");
        if ("1".equals(type)) {
            Map orderObj = orderMapper.getOrderByOrderCode(orderCode);
            if (orderObj.get("orderType").toString().indexOf("Confirm") != -1) {
                // 看一下是否在规则内自动同意了(自动同意后订单状态会修改为已取消),自动同意后会自动释放保留房
                // 如果是手动确认,在这里释放保留房
                if (!"3".equals(orderObj.get("orderStatus").toString())) {
                    // 保留房,释放保留房
                    String startTime = orderObj.get("startTime").toString().substring(0, 10);
                    String endTime = orderObj.get("endTime").toString().substring(0, 10);
                    List<String> datesInRange = DateUtils.getDatesInRange(startTime, endTime);
                    String houseId = orderObj.get("houseId").toString();
                    for (int j = 0; j < datesInRange.size() - 1; j++) {
                        String day = datesInRange.get(j);
                        Map map2 = new HashMap();
                        map2.put("houseId", houseId);
                        map2.put("startTime", day);
                        map2.put("endTime", day);
                        Map houseDayObj = houseMapper.getHouseDayList(map2).get(0);
                        int yQuantityNum = Integer.parseInt(houseDayObj.get("yQuantityNum").toString());
                        int fjsNum = Integer.parseInt(orderObj.get("fjsNum").toString());
                        Map map3 = new HashMap();
                        map3.put("yQuantityNum", yQuantityNum + fjsNum);
                        map3.put("houseId", houseId);
                        map3.put("startTime", day);
                        map3.put("endTime", day);
                        houseMapper.updateHouseDayData(map3);
                    }
                }
            }

            // 如果是同意取消,把取消订单表的状态改为1,订单表状态改为3(返回cancel)
            Map map = new HashMap();
            map.put("orderStatus", 3);
            map.put("orderId", jsonObject1.getString("parentId"));
            orderMapper.updateOrder(map);

            Map map1 = new HashMap();
            map1.put("orderStatus", 1);
            map1.put("orderId", jsonObject1.getString("orderId"));
            orderMapper.updateCancelOrder(map1);
            logService.insertOrderLog(orderCode, "人工接受订单(取消)", 2);
            return 1;
        } else {
            // 如果是拒绝取消,把取消订单表的状态改为2,订单表状态改为1(返回ok)
            Map map = new HashMap();
            map.put("orderStatus", 1);
            map.put("orderId", jsonObject1.getString("parentId"));
            orderMapper.updateOrder(map);

            Map map1 = new HashMap();
            map1.put("orderStatus", 2);
            map1.put("orderId", jsonObject1.getString("orderId"));
            orderMapper.updateCancelOrder(map1);
            logService.insertOrderLog(orderCode, "人工拒绝订单(取消)", 2);
            return 1;
        }
    }

    @Override
    public List<Map> getOrderByNoRemind(Long userId) {
        // 返回未提醒的订单
        List<Map> orderByNoRemind = orderMapper.getOrderByNoRemind(userId);
        if (orderByNoRemind.size() > 0) {
            // 将未提醒的订单改为已提醒
            orderMapper.updateNoRemindOrderByUserId(userId);
        }
        return orderByNoRemind;
    }

    @Override
    public int postCopyAndSend(Map map) {
        String orderId = map.get("orderId").toString();
        String orderCode = map.get("orderCode").toString();
        Map map1 = new HashMap();
        map1.put("orderId", orderId);
        map1.put("isIssue", 1);
        int orderType = Integer.parseInt(map.get("orderType").toString());
        logService.insertOrderLog(orderCode, "发单", 2);
        if (orderType == 1) {
            return orderMapper.updateOrder(map1);
        } else {
            return orderMapper.updateCancelOrder(map1);
        }
    }

    @Override
    public List<HotelOrder> getOrderListExport(Map map) {
        if (map.get("orderReqDateRange[0]") != null) {
            map.put("startReqTime", map.get("orderReqDateRange[0]").toString() + " 00:00:00");
        }

        if (map.get("orderReqDateRange[1]") != null) {
            map.put("endReqTime", map.get("orderReqDateRange[1]").toString() + " 23:59:59");
        }

        if (map.get("startTime[0]") != null) {
            map.put("rzStartTime", map.get("startTime[0]").toString());
        }

        if (map.get("startTime[1]") != null) {
            map.put("rzEndTime", map.get("startTime[1]").toString());
        }

        if (map.get("endTime[0]") != null) {
            map.put("ldStartTime", map.get("endTime[0]").toString());
        }

        if (map.get("endTime[1]") != null) {
            map.put("ldEndTime", map.get("endTime[1]").toString());
        }

        if (map.get("handleTime[0]") != null) {
            map.put("handleStartTime", map.get("handleTime[0]").toString());
        }

        if (map.get("handleTime[1]") != null) {
            map.put("handleEndTime", map.get("handleTime[1]").toString());
        }
        map.put("jurisdiction", jurisdictionService.getHotelDataPermissionsAndCompleteSQL());
        List<HotelOrder> orderListExport = orderMapper.getOrderListExport(map);
        return orderListExport;
    }

    @Override
    public int postUpdateOrderPrice(JSONObject jsonObject) {
        JSONArray jsonArray = jsonObject.getJSONArray("fjdj");

        // 修改订单备注
        String orderRemark = jsonObject.getString("orderRemark");
        String orderId = jsonObject.getString("orderId");
        if (orderRemark != null && !"".equals(orderRemark)) {
            Map map = new HashMap();
            map.put("orderId", orderId);
            map.put("orderRemark", orderRemark);
            orderMapper.updateOrder(map);
        }

        // 修改采购价
        int count = rpService.postYueYouEditCgj(orderId, jsonArray);

        String refundType = jsonObject.getString("refundType");
        if (refundType != null && !"".equals(refundType)) {
            // 修改异常状态,如果是提前离店,把结算价改为0
            Map map = new HashMap();
            map.put("orderId", orderId);
            map.put("refundType", refundType);
            if ("3".equals(refundType)) {
                map.put("baseAmountOriginal", 0);
            }
            orderMapper.updateOrder(map);
        }

        return count;
    }

    @Override
    public JSONObject isOrderSpecial(JSONObject jsonObject) {
        hotelSuccess.info("特殊退款场景");
        hotelSuccess.info("特殊退款场景原始报文：");
        hotelSuccess.info(JSONObject.toJSONString(jsonObject));
        JSONObject resJsonObject = new JSONObject();
        // 取出供应商订单ID
        String orderCode = jsonObject.getString("pmsOrderId");
        // 判断是否存在该订单
        Map orderByOrderCode = orderMapper.getOrderByOrderCode(orderCode);
        if (orderByOrderCode == null) {
            resJsonObject.put("code", "4001");
            resJsonObject.put("message", "Order not found");
            return resJsonObject;
        }
        String orderId = orderByOrderCode.get("orderId").toString();
        jsonObject.put("orderId", orderId);
        // 判断是否传入退款间夜列表
        if (jsonObject.get("roomNightInfoList") != null) {
            // 如果传入转换成json字符串插入数据库
            String roomNightInfoListJsonStr = JSONArray.toJSONString(jsonObject.getJSONArray("roomNightInfoList"));
            jsonObject.put("roomNightInfoList", roomNightInfoListJsonStr);
        }
        // 将特殊退款流程插入数据库
        int i = orderMapper.insertOrderSpecial(jsonObject);
        if (i > 0) {
            // 修改订单异常信息
            orderMapper.updateOrder(jsonObject);
            // 插入成功
            resJsonObject.put("code", "1000");
            resJsonObject.put("message", "Success");
        } else {
            // 插入失败
            resJsonObject.put("code", "2001");
            resJsonObject.put("message", "System error");
        }
        return resJsonObject;
    }
}